using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Checkout : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        CompareValidator1.ValueToCompare = DateTime.Now.ToString("M/d/yyyy");

        if (!IsPostBack)
        {
            this.Display();
        }
    }

    void Display()
    {
        // Thong tin thanh vien
        DataTable table = (DataTable)Session["ThanhVien"];

        lblCustomerID.Text = table.Rows[0]["CustomerID"].ToString();
        lblFullName.Text = table.Rows[0]["FullName"].ToString();
        lblOrderDate.Text = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");

        // Thong tin gio hang
        ShoppingCart Cart = (ShoppingCart)Session["ShoppingCart"];
        
        GridView1.DataSource = Cart;
        GridView1.DataBind();
    }

    protected void btnPlaceOrder_Click(object sender, EventArgs e)
    {
        String sqlOrder = "INSERT INTO Orders(CustomerID, OrderDate,  ShipAddress) VALUES(@CustomerID, @OrderDate,  @ShipAddress)";
        String sqlDetail = "INSERT INTO OrderDetails(OrderID, ProductID, UnitPrice, Quantity, Discount) VALUES(@OrderID, @ProductID, @UnitPrice, @Quantity, @Discount)";
        
        // INSERT VAO Orders
        Database.ExecuteNonQuery(sqlOrder, 
            "@CustomerID", lblCustomerID.Text,
            "@OrderDate", DateTime.Now,
          
            "@ShipAddress", txtShipAddress.Text);
        
        // Lay OrderID vua sinh ra
        String sqlOrderID = "SELECT MAX(OrderID) FROM Orders";
        int OrderID = (int)Database.ExecuteScalar(sqlOrderID);
        
        // INSERT vao OrderDetails
        ShoppingCart Cart = (ShoppingCart)Session["ShoppingCart"];
        foreach (DataRow Row in Cart.Rows)
        {
            int ProductID = (int)Row["ProductID"];
            int Quantity = (int)Row["Quantity"];
            double UnitPrice = (double)Row["UnitPrice"];
            double Discount = (double)Row["Discount"];

            Database.ExecuteNonQuery(sqlDetail, 
                "@OrderID", OrderID,
                "@ProductID", ProductID,
                "@UnitPrice", UnitPrice,
                "@Quantity", Quantity,
                "@Discount", Discount);
        }

        Cart.Clear();
        Response.Redirect("ThankYou.aspx");
    }
}
